<template>
  <div>
    <div id="table-breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/main/p1' }"
          >文件夹列表</el-breadcrumb-item
        >
        <el-breadcrumb-item>{{ path }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div>
      <div>
        <div style="width: 70%; height: 100%; float: left">
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="name" label="文件名"> </el-table-column>
            <el-table-column prop="updateTime" label="上传时间">
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="300">
              <template #default="scope">
                <el-button @click="download(scope.row)" type="text" size="small"
                  >下载</el-button
                >
                <el-button
                  @click="deleteFile(scope.row)"
                  type="text"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="width: 30%; height: 30%; float: right">
          <el-upload
            class="upload-demo"
            drag
            :file-list="fileList"
            :on-change="handleChange"
            :auto-upload="false"
            :list-type="false"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
          >
            <template #trigger>
              <el-button size="small" type="primary">选取文件</el-button>
            </template>
            <el-button
              style="margin-left: 10px"
              size="small"
              type="success"
              @click="submitUpload"
              >上传到服务器</el-button
            >
            <template #tip>
              <div class="el-upload__tip">
                只能上传 jpg/png 文件，且不超过 500kb
              </div>
            </template>
          </el-upload>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { defineComponent, ref } from "vue";
export default defineComponent({
  setup() {},
  created() {
    console.log(this.$route.query);
    this.path = this.$route.query.path;
    this.getFileListByPath(this.$route.query.path);
  },
  data() {
    return {
      path: "1222",
      field103Action: "/minio/upload1",
      field103fileList: [],
      fileList: [],
      res: "",
      tableData: "",
      filePath: "123", // 自定义参数示例：用户ID
    };
  },
  methods: {
    async getFileListByPath(path) {
      try {
        const param = {
          filePath: path,
        };
        const response = await this.$axios.post("/minio/getFileByPath", param);
        if (response.data.data) {
          this.tableData = response.data.data;
        }
      } catch (error) {
        console.error("Error fetching file explorer data:", error);
      }
    },
    goBack() {
      this.$router.push("/main/p1");
      console.log("go back");
    },
    handleChange(file, fileList) {
      this.fileList = [file.raw]; // 使用原始File对象
    },
    field103BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
      }
      //   const formData = new FormData();
      //   formData.append("file", file);
      //   formData.append("filePath", this.path);

      //   // 更新上传动作，使用FormData
      //   this.field103Action = "/minio/upload1";
      return isRightSize;
    },

    submitUpload() {
      const formData = new FormData(); // 创建一个 FormData 对象
      formData.append("file", this.fileList[0]); // 将文件添加到 FormData 对象中
      formData.append("filePath", this.path); // 将路径名添加到 FormData 对象中
      //   this.$refs.upload.submit();
      this.$axios.post("minio/upload1", formData).then((response) => {
        this.getFileListByPath(this.path);
      });
    },
    handleError(error) {
      console.error("上传失败", error);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    async getFileByPath(filePath) {
      try {
        const param = {
          filePath: filePath,
        };
        const response = await this.$axios.post("/minio/getFileListByPath/", {
          param,
        });

        if (response.data.data) {
          this.tableData = response.data.data;
        }
        // const data: FileNode[] =  response.json(); // 将返回数据类型声明为 FileNode[]
        // // 转换后端返回的 FileNode 列表为 ElementPlus Tree 组件所需的 TreeNode 格式
        // const transformedData = this.transformFileNodesToTreeNodes(data);
        // this.treeData.value = transformedData;
      } catch (error) {
        console.error("Error fetching file explorer data:", error);
      }
    }, // <- This line has been fixed by removing the extra closing curly brace
    handleSuccess(response, file) {
      this.getFileListByPath(this.path);
    },
    download(row) {
      let row1 = { ...row };
      // const param = {
      //   fileName:row1.name
      // }
      const response = this.$axios
        .get("/minio/downloadFile", {
          params: { fileName: row1.name },
          responseType: "blob", // 使axios以二进制流形式接收响应
          headers: {
            //和后端设置的一样
            "Content-Type": "application/octet-stream;charset=UTF-8",
          },
        })
        .then((response) => {
          if (response && response.data) {
            const url = window.URL.createObjectURL(new Blob([response.data]));

            const link = document.createElement("a");
            link.href = url;
            link.setAttribute("download", row1.name); // 假设 row1.name 包含完整的文件名（如 example.jpg）

            document.body.appendChild(link);
            link.click();

            // 可选：移除创建的临时链接元素
            document.body.removeChild(link);
          } else {
            console.error(
              "Failed to download file: Response data is empty or undefined."
            );
          }
        });
    },
    deleteFile(row) {
      let row1 = { ...row };
      const param = {
        fileName: row1.name,
      };
      this.$axios.post("/minio/deleteFile", param).then((response) => {
        console.log("删除成功");
      });
    },
  },
});
</script>


<style scoped></style>